#!/bin/sh

old_ver="$2"

if [ "$(apk version -t "$old_ver" '1.0.0-r0')" = '<' ]; then
	if rc-service -q garage status 2>/dev/null; then  # if running
		cat >&2 <<-EOF
		*!
		*! Garage must be stopped and prepared for migration prior to upgrade!
		*! <https://garagehq.deuxfleurs.fr/documentation/working-documents/migration-09/>
		*!
		*! In addition to this, if you're still using Sled, convert your database to
		*! LMDB by running 'garage-migrate-to-lmdb' - Sled has been already removed!
		*!
		EOF
		exit 1
	else
		cat >&2 <<-EOF
		*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*
		*! CAUTION: Read the migration guide before upgrading Garage!
		*! <https://garagehq.deuxfleurs.fr/documentation/working-documents/migration-09/>
		*!
		*! In addition to this, if you're still using Sled, convert your database to
		*! LMDB by running 'garage-migrate-to-lmdb' - Sled has been already removed!
		*!
		EOF
		if [ -t 1 ]; then  # if &1 is terminal
			echo '*! If you want to abort the upgrade, press Ctr+C.'
			echo '*! Upgrade will continue in seconds '
			count=10
			while [ $count -gt 0 ]; do
				printf "$count..." >&2
				sleep 1
				count=$(( count - 1 ))
			done
			echo '*!'
		fi
		echo '*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*' >&2
	fi

	# Copy /etc/garage.toml to /etc/garage/garage.toml *if* it was modified by user.
	if ! [ -e /etc/garage/garage.toml ] && apk audit -q /etc | grep -qx etc/garage.toml; then
		mkdir -p /etc/garage
		cp -a /etc/garage.toml /etc/garage/garage.toml
	fi
fi

exit 0
